﻿using BLL;
using Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tools;
using webui.Models;
using webui.ViewModel;

namespace webui.Areas.Admin.Controllers
{
    public class UserController : Controller
    {
        public UserInfoBLL iuserbll = new UserInfoBLL();

        public UserRoleBLL iuserrolebll = new UserRoleBLL();

        public RoleInfoBLL irolebll = new RoleInfoBLL();

        public ShopBLL shopbll = new ShopBLL();



        /// <summary>
        /// 显示 角色视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.loginname = OperateContext.Current.Usr.loginname;
            return View();
        }
        /// <summary>
        /// 加载 角色数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(PageRequst req )
        {
            //0.接收参数 page=1&rows=5
            int pageIndex = req.page == 0 ? 1 : req.page;
            int pageSize = req.rows == 0 ? 1 : req.rows;
            PageModel page = new PageModel()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageCount = 0
            };

            // var list = iuserbll.GetPageList(r => r.isDel == false, page, r => r.id, OrderByType.Desc);
            if (OperateContext.Current.Usr.loginname !=OperateContext.adminstr)
            {
                req.Shopid = (int)OperateContext.Current.Usr.Shopid;
            }
            var list = iuserbll.GetPageListRoname( page,req.KeyWord,req.Shopid);
            return Json(new DataGridModel() { rows = list, total = page.PageCount });
        }

        /// <summary>
        /// 返回添加用户页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Addrole()
        {
            SetDropDonwList();
            ViewBag.loginname = OperateContext.Current.Usr.loginname;
            return PartialView("EditRole");
        }

        [HttpPost]
        public ActionResult Addrole( UserInfo model)
        {
            if (!(string.IsNullOrEmpty(model.loginname) || string.IsNullOrEmpty(model.pwd)))
            {
                model.addtime = DateTime.Now;
                model.isDel = false;
                model.pwd =  Tools.Security.MD5(model.pwd);
                try
                {
                    var listuser = iuserbll.GetList(u => u.loginname == model.loginname && u.isDel == false).FirstOrDefault();
                    UserRole userrole = new UserRole();
                  
                    if (listuser == null)
                    {
                        if (OperateContext.Current.Usr.loginname!= OperateContext.adminstr)
                        {
                            model.Shopid = OperateContext.Current.Usr.Shopid;
                            model.ShopName = OperateContext.Current.Usr.ShopName;
                            userrole.rid = 2;  //销售角色ID
                        }
                        else
                        {
                            Shop sp = shopbll.GetById(model.Shopid);
                            model.ShopName = sp.ShopName; 
                            userrole.rid = int.Parse(Request["roleid"]);
                        }

                       iuserbll.Insert(model); //添加用户
                        var newmodel = iuserbll.GetList(u => u.loginname == model.loginname && u.isDel == false).FirstOrDefault();

                        //添加用户角色
                        userrole.isDel = false;
                        userrole.uid = newmodel.id;
                        userrole.addtime = DateTime.Now;
                        iuserrolebll.Insert(userrole);

                        return Redirect("/admin/user/index");
                    }
                    else
                    {
                        return Content("<script>alert('用户名不能和已有的账号重复'); window.location = '/admin/user/index'</script>");
                    }

                }
                catch (Exception ce)
                {
                    return OperateContext.Current.RedirectAjax("err", "添加失败" + ce.Message, null, "");
                }

            }
            else
            {
                return OperateContext.Current.RedirectAjax("err", "信息未填写完整", null, "");
            }

        }


        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult EditRole()
        {
            int rid = 0, id = 0;
            int shopid = 0;
            int.TryParse(Request["id"] ?? "0", out id);
            int.TryParse(Request["rid"] ?? "0", out rid);
            int.TryParse(Request["Shopid"] ?? "0", out shopid);
            SetDropDonwList(rid, shopid);
            var model = iuserbll.GetList(p => p.id == id).FirstOrDefault();
            model.pwd = Tools.Security.DeMD5(model.pwd);            
             V_Userinfo viewModle= model.MapTo<V_Userinfo, UserInfo>();
            viewModle.Shopid = shopid;
            viewModle.roleid = rid;
            ViewBag.loginname = OperateContext.Current.Usr.loginname;

            return PartialView(viewModle);
        }

        /// <summary>
        /// 保存修改的角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditRole(UserInfo model)
        {
            //|| string.IsNullOrEmpty(Request["roleid"].ToString()) || Request["roleid"].ToString() == "0")
            if (!(string.IsNullOrEmpty(model.loginname) || string.IsNullOrEmpty(model.pwd) ))
            {
                model.addtime = DateTime.Now;
                model.isDel = false;
                model.pwd = Tools.Security.MD5(model.pwd);
                try
                {

                    Shop sp = shopbll.GetById(model.Shopid);
                    string shopname = sp.ShopName;
                    if (OperateContext.Current.Usr.loginname != OperateContext.adminstr)
                    {
                        model.Shopid = OperateContext.Current.Usr.Shopid;
                        shopname = OperateContext.Current.Usr.ShopName;
                    }
                    else
                    {
                        UserRole userrole = iuserrolebll.GetList(p => p.uid == model.id).FirstOrDefault();
                        userrole.rid = int.Parse(Request["roleid"]); //修改角色
                        iuserrolebll.Update(userrole); ;
                    }

                    iuserbll.Update(u => new UserInfo { pwd = model.pwd,
                        username = model.username,
                        gender = model.gender,
                        remark = model.remark,
                        Shopid = model.Shopid,
                        ShopName = shopname,
                        downNum=model.downNum
                    }, u => u.id == model.id);

               
                    return Redirect("/admin/user/index");
                }
                catch (Exception ce)
                {
                    return OperateContext.Current.RedirectAjax("err", "修改失败" + ce.Message, null, "");
                }

            }
            else
            {
                return OperateContext.Current.RedirectAjax("err", "信息未填写完整", null, "");
            }
        }

        /// <summary>
        /// 删除账号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult delrole(int id)
        {

            iuserbll.DeleteById(id);
            iuserrolebll.Delete(u => u.uid == id);  //删除角色用户表 
            return OperateContext.Current.RedirectAjax("ok", "删除成功~~~", null, "");
        }

         
        /// <summary>
        /// 设置要显示的下拉列表
        /// </summary>
        /// <param name="typeid">默认选中项</param>
        private void SetDropDonwList(int selectid = 1,int shopid=0)
        {
            //var list = irolebll.GetList(p => p.isDel == false).Select(p => new SelectListItem() { Text = p.rName, Value = p.id.ToString() }).ToList();
            //if (selectid != 0)
            //{
            //    for (int i = 0; i < list.Count; i++)
            //    {
            //        if (list[i].Value == selectid.ToString())
            //        {
            //            list[i].Selected = true;
            //            break;
            //        }
            //    }
            //}
            //else
            //{
            //    list[1].Selected = true;
            //}

            // var list2 = shopbll.GetList().Select(p => new SelectListItem() { Text = p.ShopName, Value = p.ID.ToString() }).ToList();
            //if (shopid != 0)
            //{
            //    for (int i = 0; i < list.Count; i++)
            //    {
            //        if (list2[i].Value == shopid.ToString())
            //        {
            //            list2[i].Selected = true;
            //            break;
            //        }
            //    }
            //}
            //else
            //{
            //    list2[1].Selected = true;
            //}

            //  var selectList2 = new SelectList(list2, "ID", "ShopName",shopid);
            var list2 = shopbll.GetList();
            ViewBag.Shops = list2;

            // var selectList1 = new SelectList(list2, "id", "rName", selectid);

            var list = irolebll.GetList(p => p.isDel == false);
            ViewBag.Role = list;
        }




    }
}